<template>
  <div class="app-container" ref="appContainer">
    <PropTable
      ref="tableData"
      :loading="loading"
      :columns="column"
      :data="data"
      :ifUpload="true"
      :ifDataInput="true"
      :ifTemplate="true"
      :unadd="false"
      @reset="reset"
      @onSubmit="onSubmit"
      @uploadExcel="uploadExcel"
      @inputData="allDataProcessing"
      @selection-change="selectionChange"
      @downloadTemplate="downloadTemplate"
    >
      <template v-slot:operation="scope">
        <el-button
          v-if="scope.row.processed === 0"
          icon="Paperclip"
          type="primary"
          size="small"
          @click="dataProcessing(scope.row)"
        >
          数据处理
        </el-button>
        <el-button icon="Download" type="primary" size="small" @click="download(scope.row)">
          文件下载
        </el-button>
      </template>
    </PropTable>
    <AddOrEditDrawer ref="addOrEditRef" @getData="reset"></AddOrEditDrawer>
    <UploadExcelDrawer ref="uploadExcelRef" @getData="reset"></UploadExcelDrawer>
  </div>
</template>
<script lang="ts" setup name="comprehensive">
  import { ref, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import {
    postUploadRecordPageLike,
    getUploadRecordById,
  } from '@/api/controller/upload-record-controller/index'
  import { postRawRecordProcessByFile } from '@/api/controller/raw-record-controller/index'
  const loading = ref(true)
  const appContainer = ref(null)
  import PropTable from '@/components/Table/PropTable/index.vue'
  import AddOrEditDrawer from './components/addOrEditDrawer.vue'
  import UploadExcelDrawer from './components/uploadExcelDrawer.vue'
  import { ifWaiting } from '@/utils/waiting'
  const column = ref([
    { type: 'selection', width: 60, fixed: 'left', itemIf: true },
    { name: 'fileName', label: '文件名', inSearch: true, valueType: 'input' },
    { name: 'size', label: '数据条目数', width: 110 },
    { name: 'during', label: '数据时间段', width: 200 },
    { name: 'chargeName', label: '上传人', width: 100 },
    { name: 'uploadTime', label: '上传时间', width: 110 },
    { name: 'processed', label: '是否处理', width: 100, itemIf: true, showType: 'tag' },
    { name: 'remark', label: '备注' },
    { name: 'operation', slot: true, fixed: 'right', width: 220, label: '操作' },
  ])
  const data = ref(null)
  const tableData = ref(null)
  const addOrEditRef = ref()
  const uploadExcelRef = ref()
  const addOrEdit = async (row?) => {
    addOrEditRef.value.show(row)
  }
  // 删除当前项
  const del = async (row) => {
    ElMessageBox.confirm('你确定要删除当前项吗?', '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
    })
      .then(async () => {
        const result = await deleteSysUserDel({ id: row.id })
        if (result.code === 200) {
          loading.value = true
          const result = await postSysUserSearch(tableData.value?.formInline)
          data.value = result.data
          loading.value = false
          ElMessage.success('删除成功')
        }
      })
      .catch(() => {
        console.log('错误')
      })
  }

  //重置搜索条件
  const reset = async () => {
    try {
      loading.value = true
      let pageInfo = {
        pageNum: 1,
        pageSize: 15,
      }
      const result = await postUploadRecordPageLike(pageInfo)
      data.value = result.data
    } finally {
      loading.value = false
    }
  }
  //搜索
  const onSubmit = async (val) => {
    try {
      loading.value = true
      const result = await postUploadRecordPageLike(val)
      data.value = result.data
    } finally {
      loading.value = false
    }
  }
  //初始化
  onMounted(async () => {
    try {
      loading.value = true
      let pageInfo = {
        pageNum: 1,
        pageSize: 15,
      }
      const result = await postUploadRecordPageLike(pageInfo)
      data.value = result.data
    } finally {
      loading.value = false
    }
  })
  //打开上传excel文件弹窗
  const uploadExcel = () => {
    uploadExcelRef.value.show()
  }
  //文件下载
  const download = async (row) => {
    let res = await getUploadRecordById({ id: row.id })
    window.open(res.data.filePath)
  }
  const fileTag = ref([])
  const selectionChange = (val) => {
    fileTag.value = val.map((item) => {
      return item.md5
    })
  }

  //批量处理
  const allDataProcessing = async () => {
    if (fileTag.value.length !== 0) {
      ifWaiting(() => {
        postRawRecordProcessByFile(fileTag.value).then((res) => {
          downloadTxt(res)
          reset()
        })
      })
    } else {
      ElMessage.warning('请选择至少一条数据')
    }
  }
  //单条处理
  const dataProcessing = async (row) => {
    ifWaiting(() => {
      postRawRecordProcessByFile([row.md5]).then((res) => {
        downloadTxt(res)
        reset()
      })
    })
  }

  const downloadTxt = (res) => {
    let b = new Blob([res]) //拿到文件流下载对象
    let url = window.URL.createObjectURL(b) //生成文件流下载链接
    let a = document.createElement('a') //创建一个a标签用来跳转
    a.href = url // a标签 href  赋值 链接
    a.download = '数据处理结果.txt' //设置下载文件的文件名和文件格式
    document.body.appendChild(a) //将标签DOM，放置页面
    a.click()
    window.URL.revokeObjectURL(url) //释放 url 对象内存
    document.body.removeChild(a) //移除标签节点
  }

  const downloadTemplate = () => {
    var a = document.createElement('a') //创建一个<a></a>标签
    a.href = '/static/template.xlsx'
    //给a标签的href属性值加上地址，注意，这里是绝对路径，不用加 点.
    a.download = '文件上传模板.xlsx'
    //设置下载文件文件名，这里加上.xlsx指定文件类型，pdf文件就指定.fpd即可
    a.style.display = 'none' // 障眼法藏起来a标签
    document.body.appendChild(a)
    // 将a标签追加到文档对象中
    a.click() //模拟点击了a标签，会触发a标签的href的读取，浏览器就会自动下载了
    a.remove()
    // 一次性的，用完就删除a标签
  }
</script>

<style scoped>
  .edit-input {
    padding-right: 100px;
  }
  .app-container {
    flex: 1;
    display: flex;
    width: 100%;
    padding: 16px;
    box-sizing: border-box;
  }
  .cancel-btn {
    position: absolute;
    right: 15px;
    top: 10px;
  }
</style>
